import axios from "axios";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {Loading} from "element-ui";
import _ from 'lodash';
import Vue from "vue";
const request = axios.create({
	baseURL: 'http://dev.glike.top/bg/',
	timeout: 10000,
})

let loadingInstance; //loading 实例
let needLoadingRequestCount = 0; //当前正在请求的数量

function showLoading() {
	let main = document.querySelector('#app')
	if (main) {
		if (needLoadingRequestCount === 0 && !loadingInstance) {
			loadingInstance = Loading.service({
				text: '数据正在奔跑中...', 
				background: 'rgba(85, 85, 85, 0.4)',
				fullscreen: true,
			});
		}
		needLoadingRequestCount++;
	}
}
function closeLoading() {
	Vue.nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
		needLoadingRequestCount--;
		needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); // 保证大于等于0
		if (needLoadingRequestCount === 0) {
			if (loadingInstance) {
				hideLoading()
			}
		}
	});
}
//防抖：将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时， loading闪烁的问题。
//因为有时会碰到在一次请求完毕后又立刻又发起一个新的请求的情况（比如删除一个表格一行后立刻进行刷新）
//这种情况会造成连续 loading 两次，并且中间有一次极短的闪烁。通过防抖可以让 300ms 间隔内的 loading 便合并为一次，避免闪烁的情况。
var hideLoading = _.debounce(() => {
	loadingInstance.close();
	loadingInstance = null;
}, 300);

// 请求拦截
request.interceptors.request.use(
	config => {
		showLoading()
		NProgress.start()
		const identification = window.localStorage.getItem('identification')
		//identification存在，且是基于baseURL的请求
		if (identification && !(config.url.startsWith('http://') || config.url.startsWith('https://'))) {
			config.headers.identification = identification
		}
		return config
	}
)

// 响应拦截
request.interceptors.response.use(
	config => {
		NProgress.done()
		const identification = config.headers.identification
		if (identification) {
			//保存身份标识到localStorage
			window.localStorage.setItem('identification', identification)
		}
		closeLoading()
		return config.data
	}
)

export default request